﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NReader.Model.RAS;
using NReader.Service;
using Windows.UI.Xaml.Controls;
using XnReader.WinRT.Forms;

// “项目页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234233 上提供

namespace XnReader.WinRT
{
    /// <summary>
    /// 显示项预览集合的页。在“拆分布局应用程序”中，此页
    /// 用于显示及选择可用组之一。
    /// </summary>
    public sealed partial class BookReader
    {
        private ChapterInfo _chapter;

        private IList<ChapterInfo> _chapters;

        private IList<ChapterInfo> _maxChapters;

        public BookReader()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            //articleid|chapterid
            var paramArr = navigationParameter.ToString().Split('|');
            var chapterid = int.Parse(paramArr[1]);
            
            _chapter = await ChapterService.GetChapterSession(int.Parse(paramArr[0]), chapterid);
            if (_chapter == null) return;
            _maxChapters = await ChapterService.GetMaxChaptersLocal(_chapter.articleid);
            DefaultViewModel["MaxChapters"] = _maxChapters;
            DefaultViewModel["Chapter"] = _chapter;
            //从挂起恢复的操作
            if ((pageState != null
                 && pageState.ContainsKey("Page")
                 && pageState["Page"].ToString().Equals("BookReader"))
                || await Helper.GlobalUtils.CheckConnectionState() == false)
            {
                _chapters =
                     await
                     ChapterService.GetBookReaderLocal(_chapter.articleid, _chapter.webflag);
                DefaultViewModel["Chapters"] = _chapters;
                pbLoading.IsActive = false;
            }
            else
            {
                _chapters =
                    await
                    ChapterService.GetBookReader(_chapter.articleid, _chapter.webflag);
                DefaultViewModel["Chapters"] = _chapters;
                pbLoading.IsActive = false;
                await Task.Run(() => SaveBookReader());
            }
        }

        protected override void SaveState(Dictionary<string, object> pageState)
        {
            pageState["Page"] = "BookReader";
        }

        private async void ItemGridViewItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                var chapter = ((ChapterInfo) e.ClickedItem);
                //var tran = new BookTranChapterInfo { CurrentChapter = chapter };
                //if (_maxChapters != null)
                //{
                //    tran.MaxChapters = _maxChapters;
                //}
                await ChapterService.SaveChapterSession(chapter);
                var param = string.Format("{0}|{1}|{2}|{3}|{4}|current|{5}", "online",
                                          chapter.articleid,
                                          chapter.articlename,
                                          "",
                                          0,
                                          chapter.chapterid);
                Frame.Navigate(typeof (ChapterIndex), param);
                //Frame.Navigate(typeof(Chapter), chapter.chapterid);
            }
        }

        private async void LvWebsiteItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                var chapter = ((ChapterInfo)e.ClickedItem);
                await ChapterService.SaveChapterSession(chapter);
                Frame.Navigate(typeof(BookReader), string.Format("{0}|{1}", chapter.articleid, chapter.chapterid));
                //var tran = new BookTranChapterInfo { CurrentChapter = chapter };
                //if (_maxChapters != null)
                //    tran.MaxChapters = _maxChapters;
                //Frame.Navigate(typeof(BookReader), tran);
            }
        }

        /// <summary>
        /// 保存书籍信息
        /// </summary>
        /// <returns></returns>
        private async Task SaveBookReader()
        {
            if (_chapters != null)
            {
                if (_chapters != null)
                {
                    await ChapterService.SaveBookReader(_chapter.articleid, _chapter.webflag, _chapters);
                }
            }
        }
    }
}
